package com.hs.excel.demos.listenter;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.hs.excel.demos.pojo.RequestParm;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class FenzuInsertListener extends AnalysisEventListener<Map<String, String>> {

    private RequestParm requestParm;
    private Map<Integer, String> head;



    public FenzuInsertListener(RequestParm a) {
        this.requestParm = a;
    }

    @Override
    public void invoke(Map<String, String> data, AnalysisContext analysisContext) {
        if (this.requestParm.getInsertFlag()) {
            StringBuffer  stringBuffer = new StringBuffer("insert into");
            stringBuffer.append(" " + requestParm.getTableName() + "(");

            List<String> heads = new ArrayList<>(head.values());
            for (String h : heads) {
                String s = h + ",";
                stringBuffer.append(s);
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            stringBuffer.append(") ");
            stringBuffer.append("VALUES(");
            List<String> values = new ArrayList<>(data.values());
            for (String filed : values) {
                if (filed == null) {
                    String s = "'',";
                    stringBuffer.append(s);
                } else {
                    String s = "'" + filed + "'" + ",";
                    stringBuffer.append(s);
                }
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            stringBuffer.append("); ");
            Comont.insertList.add(stringBuffer.toString());
        } else {
            //单条
            if (this.requestParm.getDbType().equals("mysql")) {
                entiretyMysqlhandle(data);
            } else if (this.requestParm.getDbType().equals("oracle")){
                entiretyOracleHandle(data, head);
            }

        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (!this.requestParm.getInsertFlag()){
            if (this.requestParm.getDbType().equals("mysql")) {
                entiretyMysqlEnd(head, requestParm);
            } else if (this.requestParm.getDbType().equals("oracle")){
                entiretyOracleEnd();
            }
        }
        //需要写入的文件的路径
        String filePath = "src/main/resources/" + requestParm.getTableName().toLowerCase() + ".sql";
        try {
            File file = new File(filePath);
            FileOutputStream fos = null;
            if (!file.exists()) {
                file.createNewFile();//如果文件不存在，就创建该文件
            }
            fos = new FileOutputStream(file);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");//指定以UTF-8格式写入文件
            //遍历list
            for (String date : Comont.insertList) {
                //写
                osw.write(date);
                //每写入一个Map就换一行
                osw.write("\r\n");
            }
            //写入完成关闭流
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("所有数据解析完成！");
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        this.head = headMap;
    }

    //批量插入
    private void entiretyMysqlhandle(Map<String, String> data) {
        //单条
        List<String> values = new ArrayList<>(data.values());

        StringBuffer  stringBuffer = new StringBuffer("(");
        for (String filed : values) {
            if (filed == null) {
                String s = "'',";
                stringBuffer.append(s);
            } else {
                String s = "'" + filed + "'" + ",";
                stringBuffer.append(s);
            }
        }
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        stringBuffer.append("),");
        Comont.insertList.add(stringBuffer.toString());
    }


    //批量插入
    private void entiretyOracleHandle(Map<String, String> data, Map<Integer, String> head) {
        List<String> heads = new ArrayList<>(head.values());
        StringBuffer  stringBuffer = new StringBuffer("into " + requestParm.getTableName() + "(");
        for (String h : heads) {
            String s = h + ",";
            stringBuffer.append(s);
        }
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        stringBuffer.append(") ");
        stringBuffer.append("VALUES(");
        List<String> values = new ArrayList<>(data.values());
        for (String filed : values) {
            if (filed == null) {
                String s = "'',";
                stringBuffer.append(s);
            } else {
                String s = "'" + filed + "'" + ",";
                stringBuffer.append(s);
            }
        }
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        stringBuffer.append(")");
        Comont.insertList.add(stringBuffer.toString());
    }

    public void entiretyOracleEnd() {
        StringBuilder s = new StringBuilder("insert all");
        Comont.insertList.add(0, s.toString());
        Comont.insertList.add("SELECT * FROM dual;");
    }

    public void entiretyMysqlEnd(Map<Integer, String> head, RequestParm requestParm) {
        String s1 = Comont.insertList.get(Comont.insertList.size() - 1);
        String s2 = s1.substring(0, s1.length() - 1) + ';';
        // 获取最后一个元素的索引
        int lastIndex = Comont.insertList.size() - 1;
        // 替换最后一个元素
        Comont.insertList.set(lastIndex, s2);
        StringBuilder stringBuilder = new StringBuilder("insert into");
        stringBuilder.append(" " + requestParm.getTableName() + "(");
        List<String> heads = new ArrayList<>(head.values());
        for (String h : heads) {
            String s = h + ",";
            stringBuilder.append(s);
        }
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        stringBuilder.append(") ");
        stringBuilder.append("VALUES");
        Comont.insertList.add(0, stringBuilder.toString());
    }
}
